// dh-hospital_promotions 云对象 - 医院促销活动管理
const db = uniCloud.database();
const _ = db.command;
const { autoMountHospitalId, softDelete, batchSoftDelete } = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-hospital_promotions] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 获取促销类别文本
 */
function getPromotionCategoryText(category) {
	const categoryMap = {
		1: '用户标签促销',
		2: '商品/服务促销',
		3: 'VIP充值/消费促销',
		4: '全场促销'
	};
	return categoryMap[category] || '未知类别';
}

/**
 * 获取适用范围文本
 */
function getApplyScopeText(scope) {
	const scopeMap = {
		1: '指定商品/服务',
		2: '指定类别',
		3: '全场'
	};
	return scopeMap[scope] || '未知';
}

/**
 * 获取目标类型文本
 */
function getTargetTypeText(type) {
	const typeMap = {
		1: '服务',
		2: '产品',
		3: '全部'
	};
	return typeMap[type] || '未知';
}

/**
 * 获取折扣类型文本
 */
function getDiscountTypeText(type) {
	const typeMap = {
		1: '百分比折扣',
		2: '固定金额减免',
		3: '满减优惠',
		4: '特价'
	};
	return typeMap[type] || '未知';
}

/**
 * 获取VIP奖励类型文本
 */
function getVipRewardTypeText(type) {
	const typeMap = {
		0: '无',
		1: '充值获得VIP',
		2: '消费晋升VIP'
	};
	return typeMap[type] || '无';
}

/**
 * 获取用户标签文本
 */
function getUserTagText(tag) {
	const tagMap = {
		'new_user': '新用户',
		'vip1': 'VIP1',
		'vip2': 'VIP2',
		'vip3': 'VIP3',
		'birthday': '生日用户'
	};
	return tagMap[tag] || tag;
}

/**
 * 获取类别文本
 */
function getCategoryText(category) {
	const categoryMap = {
		'anti_inflammatory': '抗炎类',
		'cleaning': '清洁类',
		'treatment': '治疗类',
		'cosmetic': '美容类'
	};
	return categoryMap[category] || category;
}

/**
 * 格式化折扣显示
 */
function formatDiscountDisplay(promotion) {
	const { discount_type, discount_value, min_amount, special_price } = promotion;
	
	if (discount_type === 1) {
		// 百分比折扣
		const percent = Math.round(discount_value * 10);
		return `${percent}折`;
	} else if (discount_type === 2) {
		// 固定金额减免
		return `减${discount_value}元`;
	} else if (discount_type === 3) {
		// 满减优惠
		return `满${min_amount}减${discount_value}`;
	} else if (discount_type === 4) {
		// 特价
		return `特价￥${special_price}`;
	}
	return '未知折扣';
}

/**
 * 获取状态文本
 */
function getStatusText(status) {
	const statusMap = {
		1: '启用',
		2: '停用',
		3: '已结束'
	};
	return statusMap[status] || '未知';
}

/**
 * 为单个促销活动附加创建人信息和格式化文本
 */
async function enrichPromotionInfo(promotion) {
	if (!promotion) return promotion;

	// 附加创建人信息
	if (promotion.created_by) {
		try {
			const userRes = await db.collection('uni-id-users')
				.doc(promotion.created_by)
				.field({ realname_auth: true, nickname: true, username: true })
				.get();

			if (userRes.data.length > 0) {
				const user = userRes.data[0];
				promotion.creator_name = user.realname_auth?.real_name || user.nickname || user.username || '未知';
			}
		} catch (error) {
			console.error('[dh-hospital_promotions] 获取创建人信息失败:', error);
			promotion.creator_name = '未知';
		}
	}

	// 附加格式化文本
	promotion.category_text = getPromotionCategoryText(promotion.promotion_category);
	promotion.scope_text = getApplyScopeText(promotion.apply_scope);
	promotion.target_type_text = getTargetTypeText(promotion.apply_target_type);
	promotion.discount_type_text = getDiscountTypeText(promotion.discount_type);
	promotion.discount_display = formatDiscountDisplay(promotion);
	promotion.status_text = getStatusText(promotion.status);
	promotion.vip_reward_type_text = getVipRewardTypeText(promotion.vip_reward_type || 0);
	
	// 格式化用户标签
	if (Array.isArray(promotion.user_tags) && promotion.user_tags.length > 0) {
		promotion.user_tags_text = promotion.user_tags.map(tag => getUserTagText(tag)).join('、');
	} else {
		promotion.user_tags_text = '所有用户';
	}
	
	// 格式化适用类别
	if (Array.isArray(promotion.apply_categories) && promotion.apply_categories.length > 0) {
		promotion.categories_text = promotion.apply_categories.map(cat => getCategoryText(cat)).join('、');
	} else {
		promotion.categories_text = '-';
	}

	return promotion;
}

/**
 * 为促销活动列表批量附加创建人信息和格式化文本
 */
async function enrichPromotionsList(promotions) {
	if (!Array.isArray(promotions) || promotions.length === 0) {
		return promotions;
	}

	// 收集所有创建人ID
	const creatorIds = [...new Set(promotions.map(p => p.created_by).filter(Boolean))];

	if (creatorIds.length === 0) {
		// 没有创建人ID，只添加格式化文本
		promotions.forEach(promotion => {
			promotion.category_text = getPromotionCategoryText(promotion.promotion_category);
			promotion.scope_text = getApplyScopeText(promotion.apply_scope);
			promotion.target_type_text = getTargetTypeText(promotion.apply_target_type);
			promotion.discount_type_text = getDiscountTypeText(promotion.discount_type);
			promotion.discount_display = formatDiscountDisplay(promotion);
			promotion.status_text = getStatusText(promotion.status);
			promotion.vip_reward_type_text = getVipRewardTypeText(promotion.vip_reward_type || 0);
			
			if (Array.isArray(promotion.user_tags) && promotion.user_tags.length > 0) {
				promotion.user_tags_text = promotion.user_tags.map(tag => getUserTagText(tag)).join('、');
			} else {
				promotion.user_tags_text = '所有用户';
			}
			
			if (Array.isArray(promotion.apply_categories) && promotion.apply_categories.length > 0) {
				promotion.categories_text = promotion.apply_categories.map(cat => getCategoryText(cat)).join('、');
			} else {
				promotion.categories_text = '-';
			}
		});
		return promotions;
	}

	try {
		// 批量获取创建人信息
		const userRes = await db.collection('uni-id-users')
			.where({ _id: _.in(creatorIds) })
			.field({ _id: true, realname_auth: true, nickname: true, username: true })
			.get();

		// 构建创建人映射
		const creatorMap = {};
		userRes.data.forEach(user => {
			creatorMap[user._id] = user.realname_auth?.real_name || user.nickname || user.username || '未知';
		});

		// 附加信息到促销活动
		promotions.forEach(promotion => {
			// 创建人信息
			if (promotion.created_by && creatorMap[promotion.created_by]) {
				promotion.creator_name = creatorMap[promotion.created_by];
			} else {
				promotion.creator_name = '未知';
			}

			// 格式化文本
			promotion.category_text = getPromotionCategoryText(promotion.promotion_category);
			promotion.scope_text = getApplyScopeText(promotion.apply_scope);
			promotion.target_type_text = getTargetTypeText(promotion.apply_target_type);
			promotion.discount_type_text = getDiscountTypeText(promotion.discount_type);
			promotion.discount_display = formatDiscountDisplay(promotion);
			promotion.status_text = getStatusText(promotion.status);
			promotion.vip_reward_type_text = getVipRewardTypeText(promotion.vip_reward_type || 0);
			
			if (Array.isArray(promotion.user_tags) && promotion.user_tags.length > 0) {
				promotion.user_tags_text = promotion.user_tags.map(tag => getUserTagText(tag)).join('、');
			} else {
				promotion.user_tags_text = '所有用户';
			}
			
			if (Array.isArray(promotion.apply_categories) && promotion.apply_categories.length > 0) {
				promotion.categories_text = promotion.apply_categories.map(cat => getCategoryText(cat)).join('、');
			} else {
				promotion.categories_text = '-';
			}
		});
	} catch (error) {
		console.error('[dh-hospital_promotions] 批量获取创建人信息失败:', error);
		// 出错时至少添加格式化文本
		promotions.forEach(promotion => {
			promotion.creator_name = '未知';
			promotion.category_text = getPromotionCategoryText(promotion.promotion_category);
			promotion.scope_text = getApplyScopeText(promotion.apply_scope);
			promotion.target_type_text = getTargetTypeText(promotion.apply_target_type);
			promotion.discount_type_text = getDiscountTypeText(promotion.discount_type);
			promotion.discount_display = formatDiscountDisplay(promotion);
			promotion.status_text = getStatusText(promotion.status);
			promotion.vip_reward_type_text = getVipRewardTypeText(promotion.vip_reward_type || 0);
			
			if (Array.isArray(promotion.user_tags) && promotion.user_tags.length > 0) {
				promotion.user_tags_text = promotion.user_tags.map(tag => getUserTagText(tag)).join('、');
			} else {
				promotion.user_tags_text = '所有用户';
			}
			
			if (Array.isArray(promotion.apply_categories) && promotion.apply_categories.length > 0) {
				promotion.categories_text = promotion.apply_categories.map(cat => getCategoryText(cat)).join('、');
			} else {
				promotion.categories_text = '-';
			}
		});
	}

	return promotions;
}

module.exports = {
	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const uniIdToken = this.getUniIdToken();
		console.log(`[dh-hospital_promotions] 调用方法: ${methodName}, 用户ID: ${uniIdToken?.uid}`);

		const writeMethods = ['create', 'update', 'delete', 'batch'];
		if (methodName && writeMethods.some(method => methodName.toLowerCase().includes(method))) {
			if (!uniIdToken || !uniIdToken.uid) {
				throw new Error('401|未授权的访问');
			}
		}

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 根据ID查询促销活动（自动附加创建人信息和格式化文本）
	 */
	async getPromotionById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '促销活动ID不能为空');
			}

			const res = await db.collection('dh-hospital_promotions').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '促销活动不存在');
			}
			
			// 附加创建人信息和格式化文本
			const enrichedData = await enrichPromotionInfo(res.data[0]);
			return formatResponse(200, enrichedData);
		} catch (error) {
			return formatError(error, '获取促销活动失败');
		}
	},

	/**
	 * 获取促销活动列表（自动关联创建人信息和格式化文本）
	 */
	async listPromotions(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;
			
			// 构建查询条件
			const whereCondition = {};
			
			// 处理关键词搜索
			if (query.keyword) {
				const keyword = query.keyword.trim();
				if (keyword) {
					// 使用正则表达式搜索 title 或 description 字段
					whereCondition.title = new RegExp(keyword, 'i');
				}
				delete query.keyword; // 从 query 中移除 keyword 避免重复
			}
			
			// 合并其他查询条件
			Object.assign(whereCondition, query);
			
			// 默认不显示已删除记录
			whereCondition.is_deleted = false;
			
			// 执行查询
			const res = await db.collection('dh-hospital_promotions')
				.where(whereCondition)
				.skip(skip)
				.limit(limit)
				.orderBy('priority', 'desc')
				.orderBy('create_time', 'desc')
				.get();
			
			// 获取总数
			const countRes = await db.collection('dh-hospital_promotions')
				.where(whereCondition)
				.count();
			
			// 批量附加创建人信息和格式化文本
			const enrichedData = await enrichPromotionsList(res.data);
			
			return formatResponse(200, enrichedData, 'success', { count: countRes.total });
		} catch (error) {
			return formatError(error, '获取促销活动列表失败');
		}
	},

	/**
	 * 创建促销活动
	 */
	async createPromotion(data) {
		try {
			if (!data.title || !data.promotion_category) {
				return formatResponse(400, null, '活动标题和促销类别不能为空');
			}

		const uniIdToken = this.getUniIdToken();
		let promotionData = {
			...data,
			created_by: uniIdToken.uid,
			is_deleted: false,  // 软删除字段，默认未删除
			create_time: Date.now(),
			update_time: Date.now()
		};

		// 🏥 自动挂载医院ID（单一医院系统特性）
		promotionData = await autoMountHospitalId(promotionData);

		const res = await db.collection('dh-hospital_promotions').add(promotionData);
			return formatResponse(201, { _id: res.id }, '促销活动创建成功');
		} catch (error) {
			return formatError(error, '创建促销活动失败');
		}
	},

	/**
	 * 更新促销活动
	 */
	async updatePromotion(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '促销活动ID不能为空');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			await db.collection('dh-hospital_promotions').doc(id).update(updateData);
			return formatResponse(200, null, '促销活动更新成功');
		} catch (error) {
			return formatError(error, '更新促销活动失败');
		}
	},

	/**
	 * 删除促销活动
	 */
	async deletePromotion(id, reason = '') {
		try {
			if (!id) {
				return formatResponse(400, null, '促销活动ID不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-hospital_promotions', id, uniIdToken?.uid || '', reason);
			
			if (result.code === 200) {
				return formatResponse(200, null, '促销活动已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除促销活动失败');
		}
	},

	/**
	 * 批量更新促销活动
	 */
	async batchUpdatePromotions(updates) {
		try {
			if (!Array.isArray(updates) || updates.length === 0) {
				return formatResponse(400, null, '更新数据不能为空');
			}

			const promises = updates.map(item =>
				db.collection('dh-hospital_promotions').doc(item._id).update({
					...item,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${updates.length}条记录成功`);
		} catch (error) {
			return formatError(error, '批量更新失败');
		}
	},

	/**
	 * 批量删除促销活动
	 */
	async batchDeletePromotions(ids, reason = '') {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			const uniIdToken = this.getUniIdToken();
			const result = await batchSoftDelete('dh-hospital_promotions', ids, uniIdToken?.uid || '', reason);
			
			return formatResponse(result.code, result.data, result.message);
		} catch (error) {
			return formatError(error, '批量删除失败');
		}
	},

	/**
	 * 批量更新促销活动状态
	 */
	async batchUpdateStatus(ids, status) {
		try {
			if (!Array.isArray(ids) || ids.length === 0) {
				return formatResponse(400, null, 'ID列表不能为空');
			}

			if (![1, 2, 3].includes(status)) {
				return formatResponse(400, null, '状态值无效');
			}

			const promises = ids.map(id =>
				db.collection('dh-hospital_promotions').doc(id).update({
					status: status,
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `批量更新${ids.length}条记录的状态成功`);
		} catch (error) {
			return formatError(error, '批量更新状态失败');
		}
	},

	/**
	 * 更新浏览次数
	 */
	async incrementViewCount(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '促销活动ID不能为空');
			}

			await db.collection('dh-hospital_promotions').doc(id).update({
				view_count: _.inc(1)
			});
			return formatResponse(200, null, '浏览次数更新成功');
		} catch (error) {
			return formatError(error, '更新浏览次数失败');
		}
	},

	/**
	 * 更新使用次数
	 */
	async incrementUseCount(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '促销活动ID不能为空');
			}

			await db.collection('dh-hospital_promotions').doc(id).update({
				use_count: _.inc(1)
			});
			return formatResponse(200, null, '使用次数更新成功');
		} catch (error) {
			return formatError(error, '更新使用次数失败');
		}
	}
};
